﻿using System.Collections.Generic;
using HtmlAgilityPack;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using XiaoMi.JsonTypes;
//using System.Threading.Tasks;
using System.Threading;


namespace HttpTest
{
    public partial class UserInfo : Form
    {
        private static bool flag;
        private static int Count;
        CancellationTokenSource cts;

        public UserInfo()
        {
            InitializeComponent();
            BindProdList();
        }

        private void BindProdList()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("2135000541", "小米金属移动电源10400mAh（银色）");
            dic.Add("2135000509", "红米手机移动版（4G白色）");
            dic.Add("2135000510", "红米手机移动版（4G灰色）");
            dic.Add("2135200029", "红米手机移动版（4G红色）");
            dic.Add("2135100067", "红米手机联通版（4GB灰色）");
            dic.Add("2135200026", "小米手机3联通版（16G银色）");
            dic.Add("2135200027", "小米手机3联通版（16G白色）");
            dic.Add("2135200028", "小米手机3联通版（16G灰色）");
            dic.Add("2135100068", "小米路由器（黑色）");
            dic.Add("2134900002", "小米盒子");
            dic.Add("2135200033", "小米随身WIFI（黑色）");
            dic.Add("2135000502", "mi2 32G");

            BindingSource bs = new BindingSource();
            bs.DataSource = dic;
            comboBox1.DataSource = bs;
            comboBox1.DisplayMember = "Value";
            comboBox1.ValueMember = "Key";
        }

        public void QiangGou()
        {
            do
            {
                Count++;
                if (flag == false)
                {
                    AppendText("已经停止");
                    break;
                    //TimerStop();
                }
                else
                {
                    if (HttpHelper.m_CookieContainer != null)
                    {
                        var line = new StringBuilder();
                        //ClearCart();
                        this.Text = @"登陆成功";
                        string html = string.Empty;
                        //System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                        //double iiii = (DateTime.Now - startTime).TotalSeconds;
                        string urlStr = "http://order.xiaomi.com/cart/add/2135000541" + "-0-1";//"http://tc.hd.xiaomi.com/hdget?callback=hdcontrol&_="; // +iiii;
                        //urlStr = "http://order.xiaomi.com/cart/add/2135200012";
                        urlStr = "http://order.xiaomi.com/cart/add/";//手机
                        string prod = GetSelectProd();//2135000520
                        if (!string.IsNullOrEmpty(prod))
                        {
                            urlStr += prod + "-0-1";
                            html = HttpHelper.GetData(urlStr);
                            if (!string.IsNullOrEmpty(html))
                            {
                                html = GetProdAddInfo(html);
                                if (html == "成功" || html.Contains("超过最大"))
                                {
                                    AppendText("正在尝试提交订单");
                                    do
                                    {
                                        html = SubmitOrder();
                                    } while (html != "订购成功");
                                }
                                QiangGouTip(html);
                                if (html == "订购成功")
                                {
                                    TimerStop();
                                }
                            }
                            else
                            {
                                AppendText("读取内容失败！");
                            }
                        }
                        else
                        {
                            TimerStop();
                            MessageBox.Show(@"商品ID获取为空！");
                        }
                    }
                    else
                    {
                        TimerStop();
                        MessageBox.Show(@"您还没有登陆，请首先登陆！");
                    }
                }
                Thread.Sleep(100);
            }
            while (flag);
        }

        private void QiangGouTip(string html)
        {
            AppendText("正进行第" + Count + "次抢购->" + html);
        }

        /// <summary>
        /// 提交订单
        /// </summary>
        public string SubmitOrder()
        {
            //string htmlAddress = HttpHelper.GetData("http://order.xiaomi.com/user/address");
            //string addressId = string.Empty;
            //if (htmlAddress.Contains("修改</a>"))
            //{
            //    int index = htmlAddress.IndexOf("修改</a>");
            //    addressId = htmlAddress.Substring(index - 10, 8);
            //}
            string result = string.Empty;
            string submitUrl = "http://order.xiaomi.com/buy/checkout";
            string postDate = "Checkout[addressState]=0&Checkout[address]=23308821&newAddress[consignee]=&newAddress[province]=&newAddress[city]=&newAddress[district]=&newAddress[address]=&newAddress[zipcode]=&newAddress[tel]=&userAddress[consignee]=&userAddress[province]=0&userAddress[street]=&userAddress[zipcode]=&userAddress[tel]=&Checkout[pay_id]=1&Checkout[shipment_id]=1&Checkout[best_time]=1&Checkout[invoice]=1&Checkout[invoice_type]=0&Checkout[invoice_title]=&couponCode=&Checkout[couponsType]=&Checkout[couponsValue]=";
            //postDate = "Checkout%5BaddressState%5D=0&Checkout%5Baddress%5D=23308821&newAddress%5Bconsignee%5D=&newAddress%5Bprovince%5D=&newAddress%5Bcity%5D=&newAddress%5Bdistrict%5D=&newAddress%5Baddress%5D=&newAddress%5Bzipcode%5D=&newAddress%5Btel%5D=&userAddress%5Bconsignee%5D=&userAddress%5Bprovince%5D=0&userAddress%5Bstreet%5D=&userAddress%5Bzipcode%5D=&userAddress%5Btel%5D=&Checkout%5Bpay_id%5D=1&Checkout%5Bshipment_id%5D=1&Checkout%5Bbest_time%5D=1&Checkout%5Binvoice%5D=1&Checkout%5Binvoice_type%5D=0&Checkout%5Binvoice_title%5D=&couponCode=&Checkout%5BcouponsType%5D=&Checkout%5BcouponsValue%5D=";
            result = HttpHelper.PostData(submitUrl, postDate);
            if (result.Contains("支持以下各银行借记卡及信用卡") || (result.Contains("选择支付方式") && result.Contains("上次使用的支付方式")))
            {
                result = "订购成功";
            }
            else if (result.Contains("去结账") || (result.Contains("立即下单")))
            {
                result = "提交订单失败";
            }
            else
            {
                result = "订购失败";
            }
            return result;
        }

        public void QiangGouJson()
        {
            if (flag == false)
            {
                TimerStop();
            }
            else
            {
                if (HttpHelper.m_CookieContainer != null)
                {
                    var line = new StringBuilder();
                    //ClearCart();
                    this.Text = "登陆成功";
                    string html = string.Empty;
                    string UrlStr = "http://order.xiaomi.com/cart/add/2135000541";// +iiii;
                    UrlStr = "http://order.xiaomi.com/cart/add/2134900439-0-1";
                    html = HttpHelper.GetData(UrlStr);
                    string Prod = string.Empty;
                    lblAllow.Invoke(new Action(delegate()
                    {
                        Prod = comboBox1.Text;
                    }));
                    if (!string.IsNullOrEmpty(html))
                    {
                        html = GetProdAddInfo(html);
                        if (html == "成功") { html = SubmitOrder(); }
                        AppendText(html);
                        if (html == "订购成功")
                        {
                            TimerStop();
                        }
                    }
                    else
                    {
                        AppendText("读取内容失败！");
                    }
                }
                else
                {
                    TimerStop();
                    MessageBox.Show(@"您还没有登陆，请首先登陆！");
                }
            }
        }

        /// <summary>
        /// 解析返回回来页面
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string GetProdAddInfo(string html)
        {
            string result = string.Empty;
            {
                try
                {
                    string xpath = @"/html/body/div[2]/div/div/div/h2";
                    result = GetXpathStr(html, xpath).InnerHtml;
                }
                catch (Exception)
                {
                    try
                    {
                        string xpath2 = @"//*[@id='shopCartBox']/div/div[2]/div[2]/a[2]";
                        result = GetXpathStr(html, xpath2).InnerHtml;
                        if (result == "去结账")
                        {
                            result = "成功";
                        }
                    }
                    catch (Exception ex)
                    {
                        //result = ex.ToString();
                    }
                }
            }
            return result;
        }

        private HtmlNode GetXpathStr(string html, string xpath)
        {
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            HtmlNode node = doc.DocumentNode.SelectSingleNode(xpath);
            return node;
        }

        /// <summary>
        /// 开始抢购
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            button2.Enabled = true;
            System.Net.ServicePointManager.DefaultConnectionLimit = 300;
            cts = new CancellationTokenSource();
            if (checkBox1.Checked)
            {
                flag = true; btnStart.Enabled = false; button2.Enabled = true;
                NewThread(QiangGou);
            }
            else
            {
                flag = true;
                NewThread(QiangGouJson);
            }
        }

        /// <summary>
        /// 新起一个线程
        /// </summary>
        /// <param name="method"></param>
        private void NewThread(Action method)
        {
            new Thread((ParameterizedThreadStart)delegate
            {
                method();
            })
            {
                IsBackground = true
            }.Start();
        }

        /// <summary>
        /// 清空购物车
        /// </summary>
        public void ClearCart()
        {
            string urlStr = "http://order.xiaomi.com/cart/empty";
            string html = HttpHelper.GetData(urlStr);
        }

        private void DetermineCall(Action method)
        {
            //if (InvokeRequired)
            //{
            //    Invoke(method);
            //}
            //else
            //{
            //    method();
            //}
            base.BeginInvoke(method);
        }

        private void ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Form1 logon = new Form1();
            logon.Owner = this;
            logon.ShowDialog();
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            TimerStop();
        }

        private void UserInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }

        public void AppendText(string info)
        {
            DetermineCall(() =>
            {
                if (!string.IsNullOrEmpty(info))
                {
                    string tt = string.Empty;
                    if (lblAllow.Text.Contains("\n"))
                    {
                        tt = lblAllow.Text.Substring(lblAllow.Text.LastIndexOf("\n"));
                        if (tt.StartsWith("\n正在进行第"))
                        {
                            lblAllow.Text = lblAllow.Text.Substring(0, lblAllow.Text.LastIndexOf("\n"));
                        }
                    }
                    if ("\n" + info != tt)
                    {
                        if (!string.IsNullOrEmpty(lblAllow.Text)) { lblAllow.AppendText(Environment.NewLine); }
                        lblAllow.AppendText(info);//+ " → " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:fff")
                        lblAllow.SelectionStart = lblAllow.TextLength;
                        lblAllow.ScrollToCaret();
                    }
                }
            });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Invoke(new Action(() =>
              {
                  if (!string.IsNullOrEmpty(txtUrl.Text))
                  {
                      System.Diagnostics.Process.Start(txtUrl.Text);
                  }
              }));
        }

        public void TimerStop()
        {
            if (cts != null)
            {
                cts.Cancel();
            }
            DetermineCall(() =>
             {
                 flag = false; btnStart.Enabled = true; button2.Enabled = false;
             });
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //快递接口
            string html = string.Empty;
            string url = "http://sudi.qq.com/logistics/index.php/querylogis/querytraceinfo?companyCode=056yuantong&deliverid=8089389948&g_tk=951029441&g_ty=ajax";
            //url = "http://sudi.qq.com/logistics/index.php/logiscompany/getlogisCompany?t=" + new Random() + "&callback=getlogisCompanyCallback&g_tk=951029441&g_ty=ls";
            var result = HttpHelper.GetDataQQKD(url);
            string dddd = result.Replace("try{getlogisCompanyCallback(", "").Replace(")}catch(e){}", "");
            var xml = JsonConvert.DeserializeObject<KDQQJson>(dddd);
            var ddddd = xml.data;
            var data = JsonConvert.DeserializeObject<KDInfo>(result);
            result = data.traceinfo.Replace("|", Environment.NewLine);
            MessageBox.Show(result);
            ////System.Threading.Tasks.Task.Run((Action)AddFilelog);
        }

        private void AddFilelog()
        {
            for (int i = 2135200000; i < 3135200000; i++)
            {
                using (StreamWriter SW = File.AppendText("C:\\Sample.txt"))
                {
                    string result = GetProdStatus(i + "").Replace("缺货。请填写 缺货登记", "").Replace("商品", "").Replace(" ", "");
                    string str = "编号:" + i + "     " + result;
                    SW.WriteLine(str);
                    lblAllow.Invoke(new Action(delegate()
                    {
                        lblAllow.Text = str;
                    }));
                }
            }
        }

        /// <summary>
        /// 查看产品状态
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        private string GetProdStatus(string i)
        {
            string UrlStr = string.Format("http://order.xiaomi.com/event/selectPacket/goodsid/{0}", i);
            string html = HttpHelper.GetData(UrlStr);
            string result = string.Empty;
            try
            {
                string xpath = @"/html/body/div[2]/div/div/div/h2";
                result = GetXpathStr(html, xpath).InnerText;
            }
            catch (Exception)
            {
                result = "";
            }
            return result;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Invoke(new Action(() =>
            {
                string str = GetProdStatus(GetSelectProd());
                MessageBox.Show(str);
            }));
        }

        /// <summary>
        /// 获取当前选择的产品
        /// </summary>
        /// <returns></returns>
        private string GetSelectProd()
        {
            string prod = string.Empty;
            Invoke(new Action(() =>
            {
                prod = comboBox1.SelectedValue.ToString();
            }));
            return prod;
        }

        private void 清空购物车ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Invoke(new Action(() =>
           {
               if (HttpHelper.m_CookieContainer != null)
               {
                   ClearCart();
                   MessageBox.Show("清空成功");
               }
               else
               {
                   MessageBox.Show("没有登陆,请先登录");
               }
           }));
        }

    }
}
